/*
 *    Copyright 2022 jacky4631 shen ji email:121659050@qq.com
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dataoke.shoppingguide.app773026.activity.search;

import static com.dataoke.shoppingguide.app773026.bean.Constants.ALL_ITEM_LIST_URL;
import static com.dataoke.shoppingguide.app773026.bean.Constants.HOT_KEY_URL;
import static com.dataoke.shoppingguide.app773026.bean.Constants.PRODUCT_ID_KEY;
import static com.dataoke.shoppingguide.app773026.bean.Constants.PRODUCT_LIST_URL;
import static com.dataoke.shoppingguide.app773026.bean.Constants.RANKING_LIST_URL;
import static com.dataoke.shoppingguide.app773026.bean.Constants.SEARCH_ASSOCIATIONAL_URL;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alibaba.fastjson.JSON;
import com.dataoke.shoppingguide.app773026.activity.detail.ProductDetailActivity;
import com.dataoke.shoppingguide.app773026.adapter.ProductListAdapter;
import com.dataoke.shoppingguide.app773026.adapter.SearchHotListAdapter;
import com.dataoke.shoppingguide.app773026.bean.AllItemResBean;
import com.dataoke.shoppingguide.app773026.bean.HotKeyResBean;
import com.dataoke.shoppingguide.app773026.bean.ProductItemBean;
import com.dataoke.shoppingguide.app773026.bean.RankingBean;
import com.dataoke.shoppingguide.app773026.bean.RankingResBean;
import com.dataoke.shoppingguide.app773026.bean.SearchAssociationalDataBean;
import com.dataoke.shoppingguide.app773026.bean.SearchAssociationalResBean;
import com.dataoke.shoppingguide.app773026.util.HttpTools;
import com.dataoke.shoppingguide.app773026.widget.FloatLayout;

import com.dataoke.shoppingguide.app773026.R;
import com.dataoke.shoppingguide.app773026.base.activities.BackActivity;
import com.dataoke.shoppingguide.app773026.widget.RecyclerRefreshLayout;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 新版搜索界面
 * @author: shen ji
 * @date: 2022/3/15
 * @email: 121659050@qq.com
 * @wechat: jacky4631
 */
public class SearchActivity extends BackActivity implements View.OnClickListener,ProductListAdapter.OnItemClickListener,RecyclerRefreshLayout.SuperRefreshLayoutListener {

    @BindView(R.id.view_searcher)
    SearchView mViewSearch;
    @BindView(R.id.tv_search)
    TextView mSearch;
    @BindView(R.id.fl_hot)
    FloatLayout mHot;
    @BindView(R.id.rv_ranking_list)
    RecyclerView hostView;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    private ProductListAdapter mAdapter;
    @BindView(R.id.recyclerViewHistory)
    RecyclerView mRecyclerViewHistory;

    @BindView(R.id.refreshLayout)
    RecyclerRefreshLayout mRefreshLayout;
    @BindView(R.id.cl_hot)
    LinearLayout mHotLayout;

    private SearchHistoryAdapter mSearchAdapter;

    SearchHotListAdapter hotListAdapter;
    private int page = 1;
    private boolean replace = false;
    private String keyword;

    public static void show(Context context) {
        context.startActivity(new Intent(context, SearchActivity.class));
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_search;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        setStatusBarDarkMode();
        setDarkToolBar();
        mAdapter = new ProductListAdapter(this);
        mAdapter.setOnItemClickListener(this);
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        mRecyclerView.setAdapter(mAdapter);
        mRefreshLayout.setSuperRefreshLayoutListener(this);

        SearchView.SearchAutoComplete textView = mViewSearch.findViewById(R.id.search_src_text);
        textView.setTextSize(14);


        hotListAdapter = new SearchHotListAdapter(this);
        hotListAdapter.setOnItemClickListener((position, rankingBean) -> {
            this.keyword = rankingBean.getKeyword();
            mViewSearch.setQuery(this.keyword, false);
            mRecyclerView.setVisibility(View.VISIBLE);
            mRecyclerViewHistory.setVisibility(View.INVISIBLE);
            mHotLayout.setVisibility(View.INVISIBLE);
            onRefreshing();
        });
        hostView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        hostView.setAdapter(hotListAdapter);
        //recycler添加和删除动画
        hostView.setItemAnimator(new DefaultItemAnimator());

        mViewSearch.setOnCloseListener(() -> {
            // 阻止点击关闭按钮 collapse icon
            return true;
        });
        mViewSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
//                mViewSearch.clearFocus();
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if(!TextUtils.isEmpty(newText)) {
                    mRecyclerViewHistory.setVisibility(View.VISIBLE);
                    mHotLayout.setVisibility(View.INVISIBLE);
                    mRecyclerView.setVisibility(View.INVISIBLE);
                } else {
                    mRecyclerViewHistory.setVisibility(View.INVISIBLE);
                    mHotLayout.setVisibility(View.VISIBLE);
                    mRecyclerView.setVisibility(View.INVISIBLE);
                    return false;
                }
                try {
                    String url = String.format(SEARCH_ASSOCIATIONAL_URL, URLEncoder.encode(newText, "UTF-8"));
                    HttpTools.get(url, new Callback() {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                            Log.e("HaodankuListFragment", url + e.getMessage());
                        }

                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                            try {
                                SearchAssociationalResBean productListBean = JSON.parseObject(response.body().string(), SearchAssociationalResBean.class);
                                if(productListBean.getCode() == 200) {

                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            mSearchAdapter.clear();
                                            mSearchAdapter.addAll(productListBean.getData());
                                            mSearchAdapter.notifyDataSetChanged();
                                        }
                                    });
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return false;
            }
        });
        mSearchAdapter = new SearchHistoryAdapter(this);
        mRecyclerViewHistory.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerViewHistory.setAnimation(null);
        mRecyclerViewHistory.setAdapter(mSearchAdapter);
        mSearchAdapter.setOnItemClickListener((position) -> {
            SearchAssociationalDataBean item = mSearchAdapter.getItem(position);
            this.keyword = item.getKeyWord();
            mViewSearch.setQuery(this.keyword, false);
            mRecyclerView.setVisibility(View.VISIBLE);
            mRecyclerViewHistory.setVisibility(View.INVISIBLE);
            mHotLayout.setVisibility(View.INVISIBLE);
            onRefreshing();
        });
        mHot.setOnItemClickListener(key -> {
            this.keyword = key;
            mViewSearch.setQuery(this.keyword, false);
            mRecyclerView.setVisibility(View.VISIBLE);
            mRecyclerViewHistory.setVisibility(View.INVISIBLE);
            mHotLayout.setVisibility(View.INVISIBLE);
            onRefreshing();
        });
        requestHotKey();
        requestRankingList();
    }

    @OnClick({R.id.tv_search})
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_search:
                if(mSearch.getText().equals("取消")) {
                    this.finish();
                } else {
                }
        }


    }
    protected void requestHotKey() {

        HttpTools.get(HOT_KEY_URL, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("HaodankuListFragment", HOT_KEY_URL + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                try {
                    HotKeyResBean resBean = JSON.parseObject(response.body().string(), HotKeyResBean.class);
                    if(resBean.getCode() == 200) {
                        runOnUiThread(() -> mHot.setData(resBean.getData().getRecentlyKeyWord().stream().map(hotKeyRecentlyBean -> hotKeyRecentlyBean.getKeyWord()).collect(Collectors.toList())));

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    protected void requestRankingList() {

        HttpTools.get(RANKING_LIST_URL, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("HaodankuListFragment", RANKING_LIST_URL + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                try {
                    RankingResBean resBean = JSON.parseObject(response.body().string(), RankingResBean.class);
                    if(resBean.getCode() == 200) {
                        runOnUiThread(() -> {
                            List<RankingBean> rankingBeans = resBean.getData().getRankingList();
                            rankingBeans.remove(rankingBeans.size() -1);
                            hotListAdapter.setData(rankingBeans);
//                            mViewSearch.setQueryHint(resBean.getData().getRankingList().get(0).getKeyword());
                        });

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    public void onItemClick(int position, ProductItemBean itemBean) {
        Intent intent = new Intent(this, ProductDetailActivity.class);
        intent.putExtra(PRODUCT_ID_KEY, itemBean.getId());
        this.startActivity(intent);
    }


    @Override
    public void onRefreshing() {
        replace = true;
        page = 1;
        requestData();
    }

    @Override
    public void onLoadMore() {
        page++;
        requestData();
    }

    @Override
    public void onScrollToBottom() {
        page++;
        requestData();
    }

    protected void requestData() {
        mViewSearch.clearFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mViewSearch.getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
        if (TextUtils.isEmpty(keyword)) {
//            showSearchFailure(R.string.search_keyword_empty_error);
//            showViewStatus(View.VISIBLE);
//            onComplete();
            return;
        }
//        showViewStatus(View.GONE);
//        showAddHistory(keyword);
//        mKeyword = keyword;

        try {
            String url = String.format(ALL_ITEM_LIST_URL, page) + "&keyword=" + URLEncoder.encode(keyword, "UTF-8");
            HttpTools.get(url, new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.e("HaodankuListFragment", String.format(PRODUCT_LIST_URL, 1) + e.getMessage());
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    try {
                        AllItemResBean productListBean = JSON.parseObject(response.body().string(), AllItemResBean.class);
                        if(productListBean.getCode() == 200) {
                            refreshData(productListBean.getData().getItems());

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    protected void refreshData(List<ProductItemBean> items) {
        runOnUiThread(() -> {
            if(replace) {
                mAdapter.setData(items);
            } else {
                mAdapter.addData(items);
            }

            replace = false;
            mRefreshLayout.setRefreshing(false);
            mRefreshLayout.setOnLoading(false);
        });
    }
}
